Calculating Totals Using SUM in MySQL
Course: MySQL Training
Topic: Calculating Totals Using the SUM() Aggregate Function
Course Link: MySQL Training Course
Demo Link: Register for a Course Demo
1. Introduction to Calculating Totals Using SUM()
In MySQL, the SUM() aggregate function is used to calculate the total of numeric values stored in a table column. It adds together all non-NULL values in the specified column and returns a single result representing their sum.
The SUM() function is commonly used in sales reports, financial calculations, inventory management, payroll systems, order analysis, and business dashboards. For example, a company can use SUM() to calculate total sales revenue, total product quantities sold, total employee salaries, or total payments received.
Instead of retrieving every row and adding the values manually, SQL allows you to perform the calculation directly in the database.
Example
Suppose a table named sales contains the following records:
| sale_id |
product_name |
amount |
| 1 |
Laptop |
50000 |
| 2 |
Keyboard |
1500 |
| 3 |
Mouse |
800 |
| 4 |
Monitor |
12000 |
To calculate the total sales amount, use:
SELECT SUM(amount) AS total_sales
FROM sales;
Output:
The result is the sum of all values in the amount column: 50000 + 1500 + 800 + 12000 = 64300.
2. Learning Objectives
After completing this topic, you will be able to:
- Understand the purpose and syntax of the
SUM() function.
- Calculate totals for numeric columns in MySQL tables.
- Use aliases to provide meaningful names for calculated results.
- Combine
SUM() with WHERE to calculate totals for selected records.
- Calculate totals for categories using
GROUP BY.
- Filter grouped totals using
HAVING.
- Use
SUM() with conditional expressions such as CASE.
- Understand how NULL values affect aggregate calculations.
- Apply
SUM() to real-world sales, payment, inventory, and employee datasets.
- Identify common errors and follow best practices for accurate totals.
3. What Is the SUM() Function?
The SUM() function is an aggregate function in MySQL that adds numeric values from a column or expression. An aggregate function processes multiple rows and produces a summarized result.
3.1 Definition
SUM(expression) evaluates the specified numeric expression for the rows being processed and returns the total of its non-NULL results.
3.2 Basic Syntax
SELECT SUM(column_name) AS total_value
FROM table_name;
Explanation:
SELECT specifies the value or calculation to retrieve.
SUM() adds the numeric values.
column_name identifies the numeric column or expression being summed.
AS total_value assigns a readable column alias to the result.
FROM table_name specifies the table containing the data.
3.3 Important Characteristics
SUM() is an aggregate function.
- It is normally used with numeric columns or numeric expressions.
- It ignores NULL values when calculating the sum.
- It returns one result for the selected set of rows when used without grouping.
- It can calculate an overall total or a separate total for each group.
- It can be combined with filtering and conditional expressions.
- For an empty input set, or when all values being aggregated are NULL,
SUM() returns NULL.
4. Creating a Sample Database and Table
To practise the SUM() function, create a database and a sample table containing sales transactions.
4.1 Create a Database
CREATE DATABASE company_db;
This statement creates a database named company_db.
4.2 Select the Database
USE company_db;
The USE statement selects the database in which subsequent SQL statements will run.
4.3 Create the Sales Table
CREATE TABLE sales (
sale_id INT PRIMARY KEY,
product_name VARCHAR(100),
category VARCHAR(50),
quantity INT,
amount DECIMAL(12, 2),
sale_date DATE,
payment_status VARCHAR(20)
);
This table stores individual sales records. The amount column uses DECIMAL(12, 2), which is suitable for many monetary values because it stores a fixed number of decimal places.
4.4 Insert Sample Records
INSERT INTO sales
(sale_id, product_name, category, quantity, amount, sale_date, payment_status)
VALUES
(1, 'Laptop', 'Electronics', 2, 100000.00, '2026-01-05', 'Paid'),
(2, 'Keyboard', 'Accessories', 5, 7500.00, '2026-01-08', 'Paid'),
(3, 'Mouse', 'Accessories', 10, 8000.00, '2026-01-12', 'Pending'),
(4, 'Monitor', 'Electronics', 3, 36000.00, '2026-02-02', 'Paid'),
(5, 'Printer', 'Electronics', 2, 24000.00, '2026-02-10', 'Pending'),
(6, 'Desk', 'Furniture', 4, 32000.00, '2026-02-15', 'Paid'),
(7, 'Chair', 'Furniture', 6, 18000.00, '2026-03-01', 'Paid'),
(8, 'Webcam', 'Accessories', 4, 12000.00, '2026-03-06', 'Pending');
These sample records will be used in the following examples. The amount represents the total amount recorded for each sale, rather than the price of one individual unit.
4.5 View the Records
SELECT *
FROM sales;
Viewing the data before applying an aggregate function helps you verify the records and understand the expected result.
5. Calculating the Total of a Numeric Column
The simplest use of SUM() is to calculate the total of all values in one numeric column.
5.1 Calculate Total Sales
SELECT SUM(amount) AS total_sales
FROM sales;
Expected output:
The query adds all eight values in the amount column. The result is the combined amount of every sales record in the table.
5.2 Calculate Total Quantity Sold
SELECT SUM(quantity) AS total_quantity
FROM sales;
Expected output:
This query adds the quantities recorded in all sales transactions. It does not count the number of rows; it adds the actual numeric values in the quantity column.
5.3 Calculate Multiple Totals in One Query
SELECT
SUM(quantity) AS total_quantity,
SUM(amount) AS total_sales
FROM sales;
Expected output:
| total_quantity |
total_sales |
| 36 |
237500.00 |
You can use multiple aggregate expressions in a single query to produce a compact summary of the table.
6. Using Aliases with SUM()
An alias is a temporary name assigned to a result column. Aliases make aggregate results easier to understand, especially when they are displayed in reports or applications.
6.1 Using the AS Keyword
SELECT SUM(amount) AS total_revenue
FROM sales;
Here, total_revenue is the heading displayed for the calculated value.
6.2 Using a Descriptive Alias
SELECT
SUM(amount) AS "Total Sales Amount"
FROM sales;
A descriptive alias can make the result more readable. For reusable queries and application code, simple aliases such as total_sales are often easier to reference.
6.3 Why Aliases Are Useful
- They replace generic expression headings with meaningful names.
- They improve readability in reports and dashboards.
- They make result columns easier to interpret.
- They help communicate the purpose of each calculation.
7. Using SUM() with WHERE
The WHERE clause filters rows before the aggregate function calculates the total. This allows you to calculate a total for records that meet a specific condition.
7.1 Total Sales for Electronics
SELECT SUM(amount) AS electronics_sales
FROM sales
WHERE category = 'Electronics';
Expected output:
| electronics_sales |
| 160000.00 |
Only rows where the category is Electronics are included in the calculation. The amounts for Laptop, Monitor, and Printer are added together.
7.2 Total Sales for Paid Transactions
SELECT SUM(amount) AS paid_sales
FROM sales
WHERE payment_status = 'Paid';
Expected output:
This query calculates the total amount associated with records marked as Paid. The status condition determines which rows are included.
7.3 Total Sales Above a Date Threshold
SELECT SUM(amount) AS sales_after_january
FROM sales
WHERE sale_date >= '2026-02-01';
This query adds amounts from records dated February 1, 2026, or later. A date condition is useful for monthly, quarterly, or custom-period reporting.
7.4 Combining Multiple Conditions
SELECT SUM(amount) AS paid_electronics_sales
FROM sales
WHERE category = 'Electronics'
AND payment_status = 'Paid';
This calculation includes only electronics transactions whose payment status is Paid. Multiple conditions can be combined using operators such as AND and OR.
8. Calculating Totals by Category Using GROUP BY
When you need a separate total for each category rather than one overall total, use GROUP BY with SUM(). MySQL divides the selected records into groups and calculates the sum within each group.
8.1 Total Sales for Each Category
SELECT
category,
SUM(amount) AS category_sales
FROM sales
GROUP BY category;
Expected output:
| category |
category_sales |
| Accessories |
27500.00 |
| Electronics |
160000.00 |
| Furniture |
50000.00 |
Each category appears once in the output, with its corresponding sales total. The order of rows is not guaranteed unless an ORDER BY clause is specified.
8.2 Total Quantity by Category
SELECT
category,
SUM(quantity) AS total_quantity
FROM sales
GROUP BY category;
This query calculates the total quantity recorded for each product category.
8.3 Grouping by More Than One Column
SELECT
category,
payment_status,
SUM(amount) AS total_amount
FROM sales
GROUP BY category, payment_status;
This query produces a separate total for each combination of category and payment status. For example, Electronics/Paid and Electronics/Pending are treated as different groups.
9. Filtering Aggregate Results with HAVING
The HAVING clause filters groups after aggregate calculations have been performed. It is useful when you want to display only categories or groups whose total meets a condition.
9.1 Categories with Sales Above a Threshold
SELECT
category,
SUM(amount) AS category_sales
FROM sales
GROUP BY category
HAVING SUM(amount) > 30000;
Expected output:
| category |
category_sales |
| Electronics |
160000.00 |
| Furniture |
50000.00 |
Accessories is excluded because its total does not exceed 30000.
9.2 WHERE vs HAVING
| WHERE |
HAVING |
| Filters individual rows before grouping. |
Filters groups after aggregation. |
| Commonly uses conditions on regular columns. |
Commonly uses conditions on aggregate results. |
Example: WHERE category = 'Electronics' |
Example: HAVING SUM(amount) > 30000 |
9.3 Using WHERE and HAVING Together
SELECT
category,
SUM(amount) AS paid_sales
FROM sales
WHERE payment_status = 'Paid'
GROUP BY category
HAVING SUM(amount) > 20000;
First, MySQL selects paid transactions. It then groups the selected rows by category, calculates the total for each category, and finally returns only groups whose total exceeds 20000.
10. Using SUM() with ORDER BY
The ORDER BY clause sorts aggregate results. It is useful for identifying categories with the highest or lowest totals.
10.1 Sort Categories by Highest Sales
SELECT
category,
SUM(amount) AS category_sales
FROM sales
GROUP BY category
ORDER BY category_sales DESC;
The DESC keyword sorts the category totals from highest to lowest.
10.2 Sort Categories by Lowest Sales
SELECT
category,
SUM(amount) AS category_sales
FROM sales
GROUP BY category
ORDER BY category_sales ASC;
The ASC keyword sorts the totals from lowest to highest. It is also the default sort direction when no direction is specified.
10.3 Display the Top Two Categories
SELECT
category,
SUM(amount) AS category_sales
FROM sales
GROUP BY category
ORDER BY category_sales DESC
LIMIT 2;
This query returns the two categories with the highest total sales. When several groups have identical totals, add a secondary sort column if you need deterministic ordering.
11. Using SUM() with CASE for Conditional Totals
The CASE expression allows you to calculate totals that include only values satisfying a condition. This technique is commonly called conditional aggregation.
11.1 Total Amount for Paid Transactions
SELECT
SUM(
CASE
WHEN payment_status = 'Paid' THEN amount
ELSE 0
END
) AS paid_total
FROM sales;
For each row, the CASE expression returns the amount when the status is Paid and zero otherwise. The SUM() function adds the resulting values.
11.2 Calculate Paid and Pending Totals Together
SELECT
SUM(CASE
WHEN payment_status = 'Paid' THEN amount
ELSE 0
END) AS paid_total,
SUM(CASE
WHEN payment_status = 'Pending' THEN amount
ELSE 0
END) AS pending_total
FROM sales;
This query returns separate totals for paid and pending transactions in one row.
11.3 Conditional Totals by Category
SELECT
category,
SUM(CASE
WHEN payment_status = 'Paid' THEN amount
ELSE 0
END) AS paid_total,
SUM(CASE
WHEN payment_status = 'Pending' THEN amount
ELSE 0
END) AS pending_total
FROM sales
GROUP BY category;
This technique is useful for summary reports that compare multiple statuses, sales channels, or transaction types side by side.
12. Understanding NULL Values in SUM()
In MySQL, NULL represents a missing or unknown value. The SUM() function ignores NULL values and adds the remaining non-NULL values.
12.1 Example with NULL Values
CREATE TABLE payments (
payment_id INT PRIMARY KEY,
amount DECIMAL(10, 2)
);
INSERT INTO payments (payment_id, amount)
VALUES
(1, 100.00),
(2, 200.00),
(3, NULL),
(4, 300.00);
SELECT SUM(amount) AS total_payments
FROM payments;
Expected output:
The NULL value is ignored. The calculation is 100 + 200 + 300 = 600.
12.2 SUM() When All Values Are NULL
SELECT SUM(amount) AS total_amount
FROM payments
WHERE amount IS NULL;
This query returns NULL because the selected rows contain no non-NULL amount values. An aggregate query over an empty input set also returns NULL for SUM().
12.3 Using COALESCE() to Display Zero
SELECT COALESCE(SUM(amount), 0) AS total_amount
FROM payments
WHERE amount IS NULL;
COALESCE() returns the first non-NULL expression. In this example, it displays zero if SUM(amount) returns NULL. Use this approach when a report should display zero instead of a blank or NULL total.
13. Calculating Monthly and Date-Based Totals
Business reports frequently require totals over a specific date range. The WHERE clause can filter the records by date before SUM() calculates the result.
13.1 Total Sales Within a Date Range
SELECT SUM(amount) AS period_sales
FROM sales
WHERE sale_date >= '2026-02-01'
AND sale_date < '2026-03-01';
This query calculates sales for February 2026. Using a start date inclusive and the next period's start exclusive is a useful pattern, particularly when working with date-time columns.
13.2 Monthly Totals
SELECT
YEAR(sale_date) AS sales_year,
MONTH(sale_date) AS sales_month,
SUM(amount) AS monthly_sales
FROM sales
GROUP BY YEAR(sale_date), MONTH(sale_date)
ORDER BY sales_year, sales_month;
The YEAR() and MONTH() functions extract the year and month from each date. Grouping by both produces one total per month and year.
13.3 Daily Totals
SELECT
sale_date,
SUM(amount) AS daily_sales
FROM sales
GROUP BY sale_date
ORDER BY sale_date;
This query produces one row per sale date, showing the total amount recorded on each date.
14. Using SUM() with Joins
You can use SUM() with joins to calculate totals using data from multiple related tables. However, you must ensure that the join does not unintentionally duplicate rows, because duplicated rows can inflate the total.
14.1 Example with Orders and Order Items
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_name VARCHAR(100)
);
CREATE TABLE order_items (
item_id INT PRIMARY KEY,
order_id INT,
product_name VARCHAR(100),
line_total DECIMAL(10, 2),
FOREIGN KEY (order_id) REFERENCES orders(order_id)
);
Suppose orders stores one row per order, while order_items stores one row per item or order line. To calculate the total value of items for each order, use:
SELECT
o.order_id,
o.customer_name,
SUM(oi.line_total) AS order_total
FROM orders o
JOIN order_items oi
ON o.order_id = oi.order_id
GROUP BY o.order_id, o.customer_name;
The join matches each order to its order items, and the grouping calculates the total of the corresponding line values.
14.2 Avoiding Duplicate Totals
- Understand the relationship between the tables before joining them.
- Check whether each order can match multiple item rows.
- Aggregate at the correct level, such as order, customer, or product.
- Avoid adding a parent-table amount repeatedly when the join produces multiple child rows.
- Do not use
SUM(DISTINCT amount) as a general fix for duplicate joins; different legitimate rows can have the same amount and would be counted only once.
15. Difference Between SUM(), COUNT(), AVG(), MIN(), and MAX()
MySQL provides several aggregate functions for summarizing data. They serve different purposes.
| Function |
Purpose |
Example |
SUM() |
Adds numeric values. |
SUM(amount) |
COUNT() |
Counts rows or non-NULL values, depending on the expression. |
COUNT(*) |
AVG() |
Calculates the average of non-NULL numeric values. |
AVG(amount) |
MIN() |
Returns the minimum value. |
MIN(amount) |
MAX() |
Returns the maximum value. |
MAX(amount) |
15.1 Comparing SUM() and COUNT()
SELECT
SUM(quantity) AS total_quantity,
COUNT(*) AS number_of_sales
FROM sales;
SUM(quantity) adds the quantity values, while COUNT(*) counts the number of rows. These results answer different questions and should not be treated as interchangeable.
15.2 Comparing SUM() and AVG()
SELECT
SUM(amount) AS total_sales,
AVG(amount) AS average_sale
FROM sales;
The total indicates the combined amount of all sales records, while the average indicates the mean amount per non-NULL amount value in the selected records.
16. Common Errors and Troubleshooting
16.1 Using a Nonexistent Column
Problem: The query refers to a column that does not exist in the table.
SELECT SUM(price)
FROM sales;
If the table does not contain a column named price, MySQL reports an unknown-column error.
Solution: Verify the table structure and use the correct column name.
DESCRIBE sales;
16.2 Applying SUM() to Text Values
Problem: The selected column stores text instead of numeric data.
Numeric aggregation should use appropriate numeric columns. MySQL may convert values in some contexts, but relying on implicit conversion can produce misleading results or warnings.
Solution: Store quantities and monetary values in suitable numeric types, and validate incoming data before calculating totals.
16.3 Incorrect Total Because of Duplicate Rows
Problem: A join returns multiple rows for a record that was expected to appear once, inflating the total.
Solution: Review the join keys, inspect the joined rows, and aggregate at the correct level before combining results where appropriate.
16.4 Using WHERE with an Aggregate Expression
Problem: A query attempts to filter on an aggregate result in the WHERE clause.
SELECT category, SUM(amount) AS category_sales
FROM sales
GROUP BY category
WHERE SUM(amount) > 30000;
This query has an invalid clause order and tries to filter using an aggregate in WHERE.
Solution: Use HAVING for conditions on aggregate results.
SELECT category, SUM(amount) AS category_sales
FROM sales
GROUP BY category
HAVING SUM(amount) > 30000;
16.5 Unexpected NULL Result
Problem: The result of SUM() is NULL instead of a numeric total.
Possible causes:
- No rows match the filtering condition.
- All selected values in the aggregated expression are NULL.
- A conditional expression produces NULL for every selected row.
Solution: Check the filter conditions, inspect the underlying data, and use COALESCE(SUM(expression), 0) if a zero result is appropriate for the report.
16.6 Incorrect Monetary Precision
Problem: Floating-point data types can introduce small precision differences in calculations.
Solution: For many financial values, use an appropriate DECIMAL type, select a suitable precision and scale, and apply rounding according to the business rules.
17. Best Practices for Using SUM()
- Use
SUM() only with values or expressions that represent meaningful numeric quantities.
- Choose an appropriate numeric data type for the column being aggregated.
- Use clear aliases such as
total_sales, total_quantity, and paid_amount.
- Apply
WHERE conditions when the total should include only specific rows.
- Use
GROUP BY when you need totals by category, customer, product, or date.
- Use
HAVING to filter groups based on aggregate results.
- Use
ORDER BY to rank or organize totals for reporting.
- Handle NULL results intentionally rather than assuming that every total will be zero or numeric.
- Check for duplicate rows when joining related tables.
- Validate aggregate results against sample data or an independently calculated total.
- Use date ranges that correctly include the intended period.
- For large datasets, ensure filtering and grouping columns are indexed where appropriate and verify query performance with execution plans.
18. Practical Exercises
Use the sales table created earlier to practise the following tasks.
Exercise 1: Calculate Total Sales
Write a query to calculate the total value of all records in the amount column.
Exercise 2: Calculate Total Quantity
Write a query to calculate the total quantity recorded across all sales transactions.
Exercise 3: Calculate Furniture Sales
Write a query to calculate the total sales amount for the Furniture category.
Exercise 4: Calculate Paid Sales
Write a query to calculate the total amount for records whose payment status is Paid.
Exercise 5: Group Totals by Category
Display each category and its total sales amount.
Exercise 6: Filter Categories by Total
Display categories whose total sales exceed 30000.
Exercise 7: Sort by Sales
Display category totals from highest to lowest.
Exercise 8: Calculate Monthly Sales
Display the total sales amount for each month in the sample dataset.
Exercise 9: Conditional Aggregation
Display the paid and pending totals as separate columns in one result row.
Exercise 10: Handle NULL Results
Create a test query that returns NULL from SUM() and then use COALESCE() to display zero instead.
19. Practice Solutions
Solution 1: Total Sales
SELECT SUM(amount) AS total_sales
FROM sales;
Solution 2: Total Quantity
SELECT SUM(quantity) AS total_quantity
FROM sales;
Solution 3: Furniture Sales
SELECT SUM(amount) AS furniture_sales
FROM sales
WHERE category = 'Furniture';
Solution 4: Paid Sales
SELECT SUM(amount) AS paid_sales
FROM sales
WHERE payment_status = 'Paid';
Solution 5: Category Totals
SELECT
category,
SUM(amount) AS category_sales
FROM sales
GROUP BY category;
Solution 6: Categories Above 30000
SELECT
category,
SUM(amount) AS category_sales
FROM sales
GROUP BY category
HAVING SUM(amount) > 30000;
Solution 7: Sort by Sales
SELECT
category,
SUM(amount) AS category_sales
FROM sales
GROUP BY category
ORDER BY category_sales DESC;
Solution 8: Monthly Sales
SELECT
YEAR(sale_date) AS sales_year,
MONTH(sale_date) AS sales_month,
SUM(amount) AS monthly_sales
FROM sales
GROUP BY YEAR(sale_date), MONTH(sale_date)
ORDER BY sales_year, sales_month;
Solution 9: Paid and Pending Totals
SELECT
SUM(CASE
WHEN payment_status = 'Paid' THEN amount
ELSE 0
END) AS paid_total,
SUM(CASE
WHEN payment_status = 'Pending' THEN amount
ELSE 0
END) AS pending_total
FROM sales;
Solution 10: Display Zero Instead of NULL
SELECT COALESCE(SUM(amount), 0) AS total_amount
FROM payments
WHERE amount IS NULL;
20. Mini Project: Sales Summary Report
Project objective: Build a basic SQL sales summary report using the SUM() aggregate function.
Project Requirements
- Calculate total sales revenue.
- Calculate total quantity sold.
- Display revenue by product category.
- Compare paid and pending amounts.
- Display monthly sales totals.
- Identify categories with totals above a chosen threshold.
- Sort category totals from highest to lowest.
Project Query 1: Overall Summary
SELECT
SUM(amount) AS total_sales,
SUM(quantity) AS total_quantity,
COUNT(*) AS total_transactions
FROM sales;
Project Query 2: Category Performance
SELECT
category,
SUM(amount) AS total_sales,
SUM(quantity) AS total_quantity
FROM sales
GROUP BY category
ORDER BY total_sales DESC;
Project Query 3: Payment Summary
SELECT
payment_status,
SUM(amount) AS total_amount
FROM sales
GROUP BY payment_status
ORDER BY total_amount DESC;
Project Query 4: Monthly Performance
SELECT
YEAR(sale_date) AS sales_year,
MONTH(sale_date) AS sales_month,
SUM(amount) AS monthly_revenue
FROM sales
GROUP BY YEAR(sale_date), MONTH(sale_date)
ORDER BY sales_year, sales_month;
Expected Learning Outcome
After completing this project, you should be able to use aggregate functions to turn individual sales transactions into meaningful totals and summaries that can support business analysis and reporting.
21. Interview Questions and Answers
Q1. What is SUM() in MySQL?
Answer: SUM() is an aggregate function that calculates the total of non-NULL numeric values in a column or expression.
Q2. What is the syntax of SUM()?
Answer: A common form is SELECT SUM(column_name) FROM table_name;.
Q3. Does SUM() include NULL values?
Answer: No. NULL values are ignored by SUM(). If there are no non-NULL values to add, the result is NULL.
Q4. Can SUM() be used with WHERE?
Answer: Yes. WHERE filters rows before the aggregate calculation, so only matching rows contribute to the sum.
Q5. What is the purpose of GROUP BY with SUM()?
Answer: GROUP BY creates groups based on one or more columns and calculates a separate sum for each group.
Q6. What is the difference between WHERE and HAVING?
Answer: WHERE filters individual rows before aggregation, while HAVING filters grouped results after aggregation.
Q7. Can multiple SUM() functions be used in one query?
Answer: Yes. You can calculate totals for multiple columns or conditional expressions in the same query.
Q8. What is conditional aggregation?
Answer: Conditional aggregation uses an expression such as CASE inside an aggregate function to include values only when certain conditions are met.
Q9. What happens when SUM() is used on an empty result set?
Answer: It returns NULL. You can use COALESCE(SUM(column_name), 0) when a zero display is appropriate.
Q10. How can you find the category with the highest total sales?
Answer: Group records by category, calculate SUM(amount), sort the result in descending order, and use LIMIT 1 if you need one result.
SELECT
category,
SUM(amount) AS total_sales
FROM sales
GROUP BY category
ORDER BY total_sales DESC
LIMIT 1;
Q11. What is the difference between SUM() and AVG()?
Answer: SUM() adds the values, while AVG() calculates their average by dividing the sum by the count of non-NULL values.
Q12. Why might SUM() return an unexpected total after a JOIN?
Answer: The join may duplicate rows, causing values to be added more than once. Review the relationship between the tables and aggregate at the correct level.
22. Quick Revision Checklist
SUM() adds non-NULL numeric values.
- Use
SELECT SUM(column_name) FROM table_name; for an overall total.
- Use an alias to give the calculated result a meaningful heading.
- Use
WHERE to filter records before calculating a total.
- Use
GROUP BY to calculate separate totals for different groups.
- Use
HAVING to filter groups based on their totals.
- Use
ORDER BY to sort totals.
- Use
CASE inside SUM() for conditional totals.
- Use
COALESCE() when you need to display zero instead of NULL.
- Check joins for duplicate rows that could inflate totals.
- Use appropriate numeric types, especially for financial values.
- Verify results against the underlying records when troubleshooting.
23. Conclusion
The SUM() function is an essential MySQL aggregate function for calculating totals from numeric data. It helps developers and analysts summarize sales, quantities, payments, salaries, and many other business values without manually adding individual records.
By combining SUM() with WHERE, GROUP BY, HAVING, ORDER BY, and conditional expressions such as CASE, you can build flexible summary queries and reports. Understanding NULL handling, data types, and duplicate rows is also important for producing accurate results.
Practise the examples and exercises in this lesson to develop confidence in using SUM() for real-world MySQL database tasks.
Learn More: Explore the MySQL Training Course and register for a course demo to continue learning SQL and database concepts.